package thread;

import java.util.concurrent.atomic.AtomicInteger;

public class Alternate {

    private final AtomicInteger num = new AtomicInteger(0);

    private final Object block = new Object();
    private int i = 0,j = 1;
    private volatile boolean flag = false;

    public static void main(String[] args) {

        Alternate alternate = new Alternate();
        alternate.alter2();
        System.out.println("end");
    }


    public void alter(){
        Thread A = new Thread(new Runnable() {
            @Override
            public void run() {
                while (num.get() <= 100) {
                    if (num.get() % 2 == 0) {
                        System.out.println("A:" + num.get());
                        num.addAndGet(1);
                    }
                }
            }
        });


        Thread B = new Thread(new Runnable() {
            @Override
            public void run() {
                while (num.get() < 100) {
                    if (num.get() % 2 == 1) {
                        System.out.println("B:" + num.get());
                        num.addAndGet(1);
                    }
                }
            }
        });

        A.start();
        B.start();



    }

    public void alter2(){
        new Thread(() -> {
            while (i < 10) {
                synchronized (block) {
                    if (flag) {
                        try {
                            block.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {

                        System.out.println(Thread.currentThread().getName()
                                + "----"  + i);
                        i = i + 2;
                        flag = true;
                        block.notifyAll();
                    }

                }
            }
        }).start();

        new Thread(() -> {
            while (j < 10) {
                synchronized (block) {
                    if (!flag) {
                        try {
                            block.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {

                        System.out.println(Thread.currentThread().getName()
                                + "----" + j);
                        j = j + 2;
                        flag = false;
                        block.notifyAll();
                    }

                }
            }
        }).start();

    }
}
